package util.thread.threadpool;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 支持定时及周期性任务执行
 *
 * @author: Lidong
 * @time: 2020/8/6 21:26
 **/
public class ScheduledThreadPoolTest {

    private static final Logger logger = LoggerFactory.getLogger(ScheduledThreadPoolTest.class);

    public static void useScheduledThreadPool() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
        executor.scheduleAtFixedRate(() -> {
            long start = System.currentTimeMillis();
            logger.info("scheduleAtFixedRate 开始执行时间:{}", DateFormat.getTimeInstance().format(new Date()));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                logger.error(e.getMessage(), e);
            }
            long end = System.currentTimeMillis();
            logger.info("scheduleAtFixedRate 执行花费时间={}m", (end - start) / 1000);
            logger.info("scheduleAtFixedRate 执行完成时间：{}", DateFormat.getTimeInstance().format(new Date()));
            logger.info("======================================");
        }, 1, 5, TimeUnit.SECONDS);
    }

    @Test
    public void test() throws InterruptedException {
        useScheduledThreadPool();
        Thread.sleep(20000);
    }
}
